<?php

/**
 * ContentController
 *
 * @author Hua yang <htmlcook@gmail.com>
 */
class ContentController extends BController
{
	public $menuRoute = '/content/index';

	/**
	 * 栏目
	 *
	 * @var Channel
	 */
	private $_channel;

	/**
	 * 获取栏目
	 *
	 * @throws CHttpException
	 * @return Channel
	 */
	public function getChannel()
	{
		if (!isset($this->_channel)) {
			if (!isset($_GET['channel_id']) || !$channel = Channel::get($_GET['channel_id'])) {
				throw new CHttpException(404, '栏目没有找到');
			}
			$this->_channel = $channel;
		}
		return $this->_channel;
	}

	/**
	 * 设置栏目
	 *
	 * @param Channel $channel
	 */
	public function setChannel(Channel $channel)
	{
		$this->_channel = $channel;
	}

	/**
	 * 处理栏目内容单页面
	 *
	 * @param int $channel_id
	 */
	public function actionPage($channel_id)
	{
		$channel = $this->getChannel();
		$modelClass = $channel->getBundleClass();
		$model = $channel->getPage();

		if (isset($_POST[$modelClass])) {
			$model->attributes = $_POST[$modelClass];
			if ($model->save()) {
				Yii::app()->getUser()->setFlash('success', '更新页面内容成功。');
				$this->redirect(array('page', 'channel_id' => $channel_id));
			}
		}

		$this->render('page', array('model' => $model));
	}

	/**
	 * @param $channel_id
	 */
	public function actionChannel($channel_id)
	{
		$this->render('channel');
	}

	/**
	 * 管理内容
	 *
	 * @param null $channel_id
	 */
	public function actionIndex($channel_id = null)
	{
		if ($channel_id === null) {
			$channels = Channel::model()->getTree();
			reset($channels);
			if ($channels) {
				$this->setChannel(current($channels));
			} else {
				Yii::app()->getUser()->setFlash('error', '还没有栏目，请创建栏目');
				$this->redirect(array('/channel/index'));
			}
		}

		$channel = $this->getChannel();
		if ($channel->type == Channel::TYPE_PAGE) {
			$this->redirect(array('page', 'channel_id'=>$channel->id));
		}elseif ($channel->type == Channel::TYPE_EMPTY) {
			$this->redirect(array('channel', 'channel_id'=>$channel->id));
		}
		$modelClass = $channel->getBundleClass();

		if (isset($_POST['doaction'])) {
			$action = !empty($_POST['action']) ? $_POST['action'] : null;
			$ids = !empty($_POST['ids']) ? $_POST['ids'] : null;
			if ($action && $ids) {
				$this->processBulkAction($action, $ids);
			}
			$this->redirect(array('index', 'channel_id' => $channel_id));
			return;
		}

		$model = new $modelClass('search');
		$model->unsetAttributes();

		if (isset($_GET[$modelClass])) {
			$model->attributes = $_GET[$modelClass];
		}

		if ($model->hasAttribute('channel_id')) {
			$model->channel_id = $channel->id;
		}

		$this->render('index', array('model' => $model, 'channel_id' => $channel_id));
	}

	/**
	 * 创建内容
	 *
	 * @param $channel_id
	 */
	public function actionCreate($channel_id)
	{
		$channel = $this->getChannel();
		$modelClass = $channel->getBundleClass();
		$model = new $modelClass;

		if (isset($_POST[$modelClass])) {
			$model->setAttributes($_POST[$modelClass]);

			if ($model->hasAttribute('user_id')) {
				$model->user_id = Yii::app()->getUser()->id;
			}

			if ($model->hasAttribute('channel_id')) {
				$model->channel_id = $channel->id;
			}

			if ($model->save()) {
				Yii::app()->getUser()->setFlash('success', $channel->getBundleName() . '创建成功');
				if (isset($_POST['_addAnother'])) {
					$url = array('create', 'channel_id' => $channel_id);
				} elseif (isset($_POST['_continue'])) {
					$url = array('update', 'channel_id' => $channel_id, 'id' => $model->id);
				} else {
					$url = array('index', 'channel_id' => $channel_id);
				}
				$this->redirect($url);
			}
		}

		$this->render('create', array('model' => $model));
	}

	/**
	 * 更新内容
	 *
	 * @param $channel_id
	 * @param integer $id
	 */
	public function actionUpdate($channel_id, $id)
	{
		$channelModel = $this->getChannel();
		$model = $this->loadModel($id);
		$modelClass = get_class($model);

		if (isset($_POST[$modelClass])) {
			$model->setAttributes($_POST[$modelClass]);

			if ($model->save()) {
				Yii::app()->getUser()->setFlash('success', $channelModel->getBundleName() . '更新成功');
				if (isset($_POST['_addAnother'])) {
					$url = array('create', 'channel_id' => $channel_id);
				} elseif (isset($_POST['_continue'])) {
					$url = array('update', 'channel_id' => $channel_id, 'id' => $model->id);
				} else {
					$url = array('index', 'channel_id' => $channel_id);
				}
				$this->redirect($url);
			}
		}

		$this->render('update', array('model' => $model));
	}

	/**
	 * 查看内容
	 *
	 * @param $channel_id
	 * @param integer $id
	 */
	public function actionView($channel_id, $id)
	{
		$model = $this->loadModel($id);
		$this->render('view', array('model' => $model));
	}

	/**
	 * 删除内容
	 *
	 * @param $channel_id
	 * @param integer $id
	 * @throws CHttpException
	 */
	public function actionDelete($channel_id, $id)
	{
		$channelModel = $this->getChannel();
		if (Yii::app()->request->isPostRequest) {
			$result = $this->loadModel($id)->delete();

			if (!isset($_GET['ajax'])) {
				$result && Yii::app()->getUser()->setFlash('success', $channelModel->getBundleName() . '删除成功');
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index', 'channel_id' => $channel_id));
			}
		} else {
			throw new CHttpException(405, '无效的请求，请重试');
		}
	}

	/**
	 * 读取模型
	 *
	 * @param integer $id
	 * @throws CHttpException
	 * @return Node
	 */
	public function loadModel($id)
	{
		$modelClass = $this->getChannel()->getBundleClass();

		if (!$model = CActiveRecord::model($modelClass)->findByPk($id)) {
			throw new CHttpException(404, '页面没有找到。');
		}

		return $model;
	}

	/**
	 * 批量处理
	 *
	 * @param string $action
	 * @param mixed $ids
	 */
	protected function processBulkAction($action, $ids)
	{
		$ids = (array)$ids;
		$count = 0;

		$staticModel = CActiveRecord::model($this->getChannel()->getBundleClass());
		switch ($action) {
			case 'draft':
				foreach ($staticModel->findAllByPk($ids) as $model) {
					$model->changeStatus(Node::STATUS_DRAFT);
				}
				break;
			case 'public':
				foreach ($staticModel->findAllByPk($ids) as $model) {
					$model->changeStatus(Node::STATUS_PUBLIC);
				}
				break;
			case 'delete':
				foreach ($staticModel->findAllByPk($ids) as $model) {
					if ($model->delete()) {
						$count++;
					}
				}
				$message = sprintf('已删除%d个%s', $count, $this->getChannel()->getBundleName());
				break;
			default:
				$method = 'bulk' . $action;
				if (method_exists($staticModel, $method)) {
					$staticModel->$method($ids);
				}
				break;
		}

		if (!isset($message)) {
			$message = '应用已执行';
		}

		Yii::app()->getUser()->setFlash('success', $message);
	}

	public function renderContentPartial($model, $view , $data=null,$return=false,$processOutput=false)
	{
		if(($viewFile=$this->getViewFileByModel($model, $view))!==false)
		{
			$output=$this->renderFile($viewFile,$data,true);
			if($processOutput)
				$output=$this->processOutput($output);
			if($return)
				return $output;
			else
				echo $output;
		}
		else
			throw new CException(Yii::t('yii','{controller} cannot find the requested view "{view}".',
				array('{controller}'=>get_class($this), '{view}'=>$view)));
	}

	public function getViewFileByModel($model, $viewName)
	{
		$viewDirectories = array(
			Yii::getPathOfAlias('frontend.backend.views.content'),
			$this->getViewPath(),
		);

		foreach ($viewDirectories as $viewDirectory) {
			$className = get_class($model);
			$viewPath =  $viewDirectory . DIRECTORY_SEPARATOR . YUtil::lcfirst($className);
			if (file_exists($viewPath)) {
				$viewPath =  $viewDirectory . DIRECTORY_SEPARATOR . YUtil::lcfirst($className);
				break;
			} else {
				while (!file_exists($viewPath )) {
					$parent = get_parent_class($className);
					if (!$parent || strtolower($parent) === strtolower('CActiveRecord')) {
						break;
					}
					$className = $parent;
					$viewPath = $viewDirectory . DIRECTORY_SEPARATOR . YUtil::lcfirst($className);
				}
			}
		}

		if (!isset($viewPath)) {
			return false;
		}

		$basePath=Yii::app()->getViewPath();
		return $this->resolveViewFile($viewName, $viewPath, $basePath);
	}

	/**
	 * 生成面包屑
	 *
	 * @param Channel $channel
	 * @return array
	 */
	protected function generateBreadcrumb(Channel $channel = null)
	{
		if ($channel === null) {
			$channel = $this->getChannel();
		}

		$breadcrumb = array('内容' => array('/content/index'));
		$parents = $channel->getParentsAll();
		foreach ($parents as $parent) {
			if ($parent->type == Channel::TYPE_PAGE) {
				$url = array('/content/page', 'channel_id' => $parent->id);
			} else if ($parent->type == Channel::TYPE_EMPTY) {
				$url = array('/content/channel', 'channel_id' => $parent->id);
			} else {
				$url = array('/content/index', 'channel_id' => $parent->id);
			}
			$breadcrumb[$parent->title] = $url;
		}
		return $breadcrumb;
	}

	protected function beforeRender($view)
	{
		if (parent::beforeRender($view)) {
			$channel = $this->getChannel();
			$this->breadcrumbs = $this->generateBreadcrumb($channel);
			$this->breadcrumbs[$channel->title] = array('index', 'channel_id' => $channel->id);
			return true;
		} else {
			return false;
		}
	}
}